package com.petdog.common.util;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.ImageIO;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 图片处理工具类
 * 提供图片缩放、裁剪等功能
 */
@Component
public class ImageUtil {
    private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);
    
    private static ImageUtil instance;
    
    @Value("${file.upload.base-path}")
    private String basePath;
    
    @Value("${file.upload.thumbnail-width:200}")
    private int thumbnailWidth;
    
    @Value("${file.upload.thumbnail-height:200}")
    private int thumbnailHeight;
    
    @Value("${file.upload.thumbnail-dir:thumbnail}")
    private String thumbnailDir;
    
    @Value("${file.upload.supported-formats:jpg,jpeg,png,gif}")
    private String[] supportedFormats;
    
    @Value("${file.upload.max-size-bytes:10485760}")
    private long maxSizeBytes;
    
    @Value("${file.upload.min-avatar-width:80}")
    private int minAvatarWidth;
    
    @Value("${file.upload.min-avatar-height:80}")
    private int minAvatarHeight;
    
    @PostConstruct
    public void init() {
        instance = this;
    }
    
    // 获取单例实例
    private static ImageUtil getInstance() {
        return instance;
    }
    
    // 缩略图宽度
    private int getThumbnailWidth() {
        return thumbnailWidth;
    }
    
    // 缩略图高度
    private int getThumbnailHeight() {
        return thumbnailHeight;
    }
    
    // 文件存储基础路径
    private static String getBaseUploadPath() {
        return getInstance().basePath;
    }
    
    // 缩略图目录
    public static String getThumbnailDir() {
        return getInstance().thumbnailDir;
    }
    
    // 获取支持的图片格式集合
    private static Set<String> getSupportedFormats() {
        return Arrays.stream(getInstance().supportedFormats)
                .map(String::toLowerCase)
                .collect(Collectors.toSet());
    }
    
    // 获取最大文件大小(字节)
    private static long getMaxSizeBytes() {
        return getInstance().maxSizeBytes;
    }
    
    // 获取头像最小宽度
    private static int getMinAvatarWidth() {
        return getInstance().minAvatarWidth;
    }
    
    // 获取头像最小高度
    private static int getMinAvatarHeight() {
        return getInstance().minAvatarHeight;
    }
    
    /**
     * 生成图片缩略图
     * @param fileName 原图片文件名
     * @return 缩略图路径，生成失败返回null
     */
    public static String generateThumbnail(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            logger.warn("文件名不能为空");
            return null;
        }
        
        String basePath = getBaseUploadPath();
        String thumbnailDir = getThumbnailDir();
        
        try {
            // 确保缩略图目录存在
            File dir = new File(basePath + File.separator + thumbnailDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 原文件路径
            String originalFilePath = basePath + File.separator + fileName;
            
            // 缩略图文件路径
            String thumbnailFileName = "thumb_" + fileName;
            String thumbnailFilePath = basePath + File.separator + thumbnailDir + File.separator + thumbnailFileName;
            
            // 使用Thumbnailator生成缩略图
            Thumbnails.of(originalFilePath)
                    .size(getInstance().getThumbnailWidth(), getInstance().getThumbnailHeight())
                    .keepAspectRatio(true)
                    .toFile(thumbnailFilePath);
            
            return thumbnailDir + File.separator + thumbnailFileName;
        } catch (IOException e) {
            logger.error("生成缩略图失败: " + e.getMessage(), e);
            return null;
        }
    }
}
